%% Fourier Transforms


lambda=2;
A=3;

Nl=10; %Number of wavelengths to sample

%Make sampling vector
Xvec=linspace(0,Nl*lambda,Nl*lambda*10)

N=length(Xvec);

%This is our signal
F = A*cos(2*pi/lambda*Xvec);



%A few others to try

%Two waves added
%F = A*cos(2*pi/lambda*Xvec)+A/2*sin(2*pi/lambda*2*Xvec) ;

%Delta
%F=zeros(N,1)'
%F(N/2)=1

%Expoential
%Xvec=(0:N-1)
%F=exp(-Xvec/(N))

%See 'help fft'

%functino for generating the wave that will multiply our signal
genWave = @(k,N) exp(-j*2*pi*(k-1)*(0:N-1)/N)

%% Show Efffects from individual waves

h=figure

for kk=1:N
    
    figure(h)
    
    %Plot our signal and FT wave
    subplot(2,1,1)
    plot(Xvec,F)
    xlabel('X')
    ylabel('F')
    hold on
    plot(Xvec,real(genWave(kk,N)),'r')
    plot(Xvec,imag(genWave(kk,N)),'g')
    legend('Our function','k wave (real)','k wave (imag)')
    hold off
    
    %Look at the multiplication
    subplot(2,1,2)
    plot(Xvec,F.*real(genWave(kk,N)),'r')
    hold on
    plot(Xvec,F.*imag(genWave(kk,N)),'g')
    xlabel('X')
    ylabel('F')
    
    Sreal=sprintf('F*kwave, sum=%g',sum(F.*real(genWave(kk,N))))
    Simag=sprintf('F*kwave, sum=%g',sum(F.*imag(genWave(kk,N))))
    
    legend({Sreal,Simag})
    hold off
    pause(1)
end

%% Our Descrete Fourier Transform


for kk=1:N
    F_k(kk)=sum(F.*genWave(kk,N));
end

%Calculate spatial frequency vector (not wave vector) K =1/lambda like f=1/T
Kvec=(1/Xvec(end))*(0:N-1)

figure
hold on
plot(Kvec,real(F_k))
plot(Kvec,imag(F_k))
plot(Kvec,abs(F_k))
xlabel('Frequency')
ylabel('F_k')
legend('real','imag','abs')

%Note the second peak above Nyquist sampling.  These can be thought of as
%negative frequencies

%% Inverse transform

%This should give us back our original signal
genWaveInv = @(k,N) exp(j*2*pi*(k-1)*(0:N-1)/N)

for kk=1:N
    F_x(kk)=1/N*sum(F_k.*genWaveInv(kk,N));
end

figure
plot(Xvec,F_x)
xlabel('X')
ylabel('F')



